<template>
  <div>
    <h1>高级用户列表</h1>
    <div class="query-form">
      <el-input v-model="queryParams.name" placeholder="请输入姓名" />
      <el-select v-model="queryParams.gender" placeholder="请选择性别">
        <el-option label="男" value="男" />
        <el-option label="女" value="女" />
      </el-select>
      <el-button @click="fetchUserList">查询</el-button>
    </div>
    <div class="outer-scroll-box" @scroll="gundong" :style="`height:${tableSettings.scrollHeight}px; overflow-y: auto;`">
      <div
        class="virtual-table-box"
        :style="`height:${tableSettings.totalHeight}px; position: relative;`"
      >
        <el-table ref="eltables" :data="virtualUserList" style="position: absolute; top: 0;" stripe>
          <el-table-column prop="id" label="ID" />
          <el-table-column prop="name" label="姓名" />
          <el-table-column prop="age" label="年龄" />
          <el-table-column prop="gender" label="性别" />
          <el-table-column prop="email" label="邮箱" />
          <el-table-column label="操作">
            <template #default="scope">
              <el-button type="primary" size="small" @click="editUser(scope.row)">编辑</el-button>
              <el-button type="danger" size="small" @click="deleteUser(scope.row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick } from 'vue';
import axios from 'axiosInstance';

// 查询参数
const queryParams = ref({
  name: '',
  gender: ''
});

const tableSettings = {
  rowHeight: 0, // 初始行高设为 0，后续动态获取
  scrollHeight: 0, // 滚动高度，后续动态计算
  initialRenderCount: 10, // 初始渲染行数
  totalHeight: 0 // 所有数据的总高度
};

let eltables = ref(null); // 表格的 dom 引用

// 根据滚动位置计算要渲染的数据范围
const gettableByScroll = (scrollTop = 0) => {
  if (tableSettings.rowHeight === 0) return;
  
  // 计算最大可滚动高度
  const maxScrollTop = tableSettings.rowHeight * userList.value.length - tableSettings.scrollHeight;
  
  // 如果滚动到底部，直接使用最大可滚动高度
  if (scrollTop >= maxScrollTop) {
    scrollTop = maxScrollTop;
  }

  let start = Math.floor(scrollTop / tableSettings.rowHeight);
  let end = Math.floor((scrollTop + tableSettings.scrollHeight) / tableSettings.rowHeight);
  
  // 确保 start 和 end 在 userList 的有效范围内
  start = Math.max(0, start);
  end = Math.min(userList.value.length, end + 1); // 加1确保最后一条数据能显示
  
  virtualUserList.value = userList.value.slice(start, end);
  
  // 保持表格的滚动位置
  nextTick(() => {
    const tableWrapper = eltables.value.$el.querySelector('.el-table__body-wrapper');
    if (tableWrapper) {
      tableWrapper.scrollTop = scrollTop - start * tableSettings.rowHeight;
    }
  });
};

// 滚动事件处理函数
const gundong = (e) => {
  // 基于滚动的距离计算出应该渲染的用户列表数据
  gettableByScroll(e.target.scrollTop);
  console.log('scrollTop:', e.target.scrollTop);
};

// 用户列表数据
const userList = ref([]);

// 真实渲染的用户列表数据
const virtualUserList = ref([]);

// 获取用户列表
const fetchUserList = async () => {
  try {
    const response = await axios.get('/api/userList', {
      params: queryParams.value
    });
    userList.value = response.data;
    console.log('userList:', userList.value); // 检查数据是否正确加载
    // 如果数据列表有值，先渲染初始行数的数据
    if (userList.value.length > 0) {
      virtualUserList.value = userList.value.slice(0, tableSettings.initialRenderCount);
      // 等待 DOM 更新后获取行高
      nextTick(() => {
        getClomusHeight();
        // 计算所有数据的总高度
        tableSettings.totalHeight = tableSettings.rowHeight * userList.value.length;
        console.log('所有数据的总高度:', tableSettings.totalHeight);
        // 重新计算虚拟列表
        gettableByScroll();
      });
    }
  } catch (error) {
    console.error('获取用户列表失败:', error);
  }
};

// 编辑用户（这里只是简单示例，可根据需求完善）
const editUser = (user) => {
  console.log('编辑用户:', user);
};

// 删除用户
const deleteUser = async (id) => {
  try {
    await axios.delete(`http://localhost:3000/api/user/${id}`);
    fetchUserList();
  } catch (error) {
    console.error('删除用户失败:', error);
  }
};

// 获取表格行高并计算滚动区域高度
const getClomusHeight = () => {
  // 如果渲染列表有值，就获取第一行的高度
  if (virtualUserList.value.length > 0) {
    // 通过 ref 获取表格的第一行的高度
    let dom = eltables.value.$el.querySelector('.el-table__body-wrapper tbody tr');
    if (dom) {
      tableSettings.rowHeight = dom.offsetHeight;
      tableSettings.scrollHeight = tableSettings.rowHeight * tableSettings.initialRenderCount;
    }
  }
};

onMounted(async () => {
  await fetchUserList();
});
</script>

<style scoped>
.query-form {
  margin-bottom: 20px;
}
.virtual-table-box {
  border: 1px solid #ccc;
}
.outer-scroll-box {
  margin: 20px 0;
  overflow: hidden;
}
</style>